<template>
	<div class="search">
		<Row>
			<Col>
			<Card>
				<Row @keydown.enter.native="handleSearch">
					<Form ref="searchForm" :model="searchForm" inline :label-width="110" class="search-form">
						<Form-item label="展商名称" prop="companyName">
							<Input type="text" v-model.trim="searchForm.companyName" placeholder="请输入展商名称" clearable style="width: 200px" />
						</Form-item>
						<Form-item label="展商英文名称" prop="companyNameEn">
							<Input type="text" v-model.trim="searchForm.companyNameEn" placeholder="请输入英文名称" clearable style="width: 200px" />
						</Form-item>
						<Form-item label="展位号" prop="standNo">
							<Input type="text" v-model.trim="searchForm.standNo" placeholder="请输入展位号" clearable style="width: 200px" />
						</Form-item>
						<FormItem label="产品类别" >
							<Cascader :data="productTypeTree" trigger="click" change-on-select  style="width:200px"
							 transfer="true" clearable @on-change="searchProductTypeChange"></Cascader>
						</FormItem>
						<Form-item style="margin-left:-35px;" class="br">
							<Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
							<Button @click="handleReset">重置</Button>
						</Form-item>
					</Form>
				</Row>
				<Row class="operation">
					<Button @click="add" type="primary" icon="md-add">添加</Button>
					<Button @click="importTableData=[];importModalVisible = true;" type="primary" icon="md-add">导入数据</Button>
					<Button @click="getDataList" icon="md-refresh">刷新</Button>
					<circleLoading v-if="operationLoading" />
				</Row>
				<Row>
					<Alert show-icon>
						已选择 <span class="select-count">{{selectCount}}</span> 项
						<a class="select-clear" @click="clearSelectAll">清空</a>
					</Alert>
				</Row>
				<Row>
					<Table :loading="loading" border :columns="columns" :data="data" ref="table" sortable="custom" @on-sort-change="changeSort"
					 @on-selection-change="changeSelect"></Table>
				</Row>
				<Row type="flex" justify="end" class="page">
					<Page :current="pageNumber" :total="total" :page-size="pageSize" @on-change="changePage" @on-page-size-change="changePageSize"
					 :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
				</Row>
			</Card>
			</Col>

		</Row>
		<input type="hidden" v-model="standFlag" />
		<Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="1000">

			<Form ref="form" :model="form" :label-width="100" :rules="formValidate">

				<FormItem label="展商名称" prop="companyName">
					<Row>
						<Col span="18">
						<Tooltip placement="right" :max-width="220" transfer content="最多可输入150个字符">
							<Input type="text" v-model.trim="form.companyName" :maxlength=150 placeholder="请输入展商名称" />
						</Tooltip>
						</Col>
					</Row>
				</FormItem>

				<FormItem label="展商英文名称" prop="companyNameEn">
					<Row>
						<Col span="18">
						<Tooltip placement="right" :max-width="220" transfer content="最多可输入300个字符">
							<Input type="text" v-model.trim="form.companyNameEn" :maxlength=300 placeholder="请输入展商名称" />
						</Tooltip>
						</Col>
					</Row>
				</FormItem>

				<FormItem v-for="(item, index) in form.stands" :key="index" :label="'展位号'" :prop="'stands.'+index+'.value'" :rules="validateStand">
					<Row>
						<Col span="18">
						<Tooltip placement="right" :max-width="220" transfer content="只能输入0-9、A-Z、-">
							<Input type="text" v-model.trim="item.value" placeholder="请输入展位号" maxlength="10"></Input>
						</Tooltip>
						</Col>
						<Col span="4" offset="1">
						<Button @click="handleRemoveStand(index)">删除</Button>
						</Col>
					</Row>
				</FormItem>
				<FormItem>
					<Row>
						<Col span="12">
						<Button type="dashed" long @click="handleAddStand('')" icon="md-add">添加展位号</Button>
						</Col>
					</Row>
				</FormItem>
				<FormItem label="产品类别" props="productTypeIds">

					<Tree ref="tree" :data="productTypes" show-checkbox @on-check-change="productChange" :check-strictly="false"></Tree>


				</FormItem>
			</Form>
			<div slot="footer">
				<Button type="text" @click="modalVisible=false">取消</Button>
				<Button type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
			</div>
		</Modal>



		<Drawer title="导入数据" closable v-model="importModalVisible" width="80%">
			<Upload action :before-upload="beforeUploadImport" accept=".xls, .xlsx">
				<Button icon="ios-cloud-upload-outline" style="margin-right:10px">上传Excel文件</Button>
				<span v-if="uploadfile.name!=''">当前选择文件：{{ uploadfile.name }}</span>
			</Upload>
			<Alert type="warning" show-icon>导入前请下载查看导入模版数据文件，确保数据格式正确，不得修改首行列名称。必需数据字段：展商名称、展位号</Alert>
			<Table :columns="importColumns" border :height="height" :data="importTableData" ref="importTable"></Table>
			<div class="drawer-footer">
				<Button @click="downloadTemple" type="info" style="position:absolute;left:15px;">下载导入模板</Button>
				<Button @click="importModalVisible=false">关闭</Button>
				<Button :loading="importLoading" :disabled="importTableData.length<=0" @click="importData" style="margin-left:5px"
				 type="primary">
					确认导入
					<span v-if="importTableData.length>0">{{importTableData.length}} 条数据</span>
				</Button>
			</div>
		</Drawer>
		<Modal :title="importModalTitle" v-model="importModalResultVisible" :mask-closable='false' :width="400">
			<div>
				<p v-if="importResult.errorDataList.length==0">全部导入成功，共计 <span style="color: #19be6b;">{{importResult.successCount}}
					</span>条数据
				</p>
				<p v-else>导入成功 <span style="color: #19be6b;">{{importResult.successCount}}</span>条数据，失败 <span style="color: #f01414;">{{importResult.errorDataList.length}}</span>条数据</p>
				<Button @click="exportErrorData" v-if="importResult.errorDataList.length>0" type="primary">下载失败数据</Button>
			</div>
			<div slot="footer">
				<Button type="text" @click="importModalResultVisible=false">取消</Button>
			</div>
		</Modal>
	</div>
</template>

<script>
	import circleLoading from "@/views/my-components/circle-loading.vue";

	import {
		addExhibitor,
		editExhibitor,
		getExhibitorList,
		deleteExhibitor,
		getAllProductType,
		importExhibitor
	} from "@/api/index";
	// 模版导入文件表数据
	import {
		tempColumns,
		tempData,
		getColumnsKey
	} from "./importTemplate";
	import excel from "@/libs/excel";
	export default {
		name: "exhibitor-manager",
		components: {
			circleLoading,
		},
		data() {
			return {
				validateStand: {
					required: true,
					message: '请输入正确的展位号',
					pattern: /^[0-9A-Z\-]{1,10}$/,
					// validator: (rule, value, callback) => {
					// 	var reg = /^[0-9A-Z\-]+$/;
					// 	if (value === null || value === undefined || value.length === 0) {
					// 		callback(new Error("请输入展位号"));
					// 	} else if (!reg.test(value)) {
					// 		callback(new Error("展位号格式错误"));
					// 	} else {
					// 		callback();
					// 	}
					// },
					trigger: 'blur'
				},
				productTypeIds:[],//用于弹窗 监听
				standFlag: 0, //强制刷新Vue视图 勿删
				productTypes: [],
				productTypeTree: [],
				loading: true, // 表单加载状态
				operationLoading: false, // 操作加载状态
				modalType: 0, // 添加或编辑标识
				modalVisible: false, // 添加或编辑显示
				modalTitle: "", // 添加或编辑标题

				//导入部分 start
				importLoading: false,
				importModalVisible: false,
				importTableData: [],
				importColumns: [],
				uploadfile: {
					name: ""
				},
				importModalResultVisible: false, // 导入结果显示
				importModalTitle: "导入结果", // 导入结果标题
				height: 510,
				importResult: {
					successCount: 0,
					errorDataList: [],
				},
				//导入部分 end
				searchForm: { // 搜索框初始化对象
					pageNumber: 1, // 当前页数
					pageSize: 10, // 页面大小
					sort: "createTime", // 默认排序字段
					order: "desc", // 默认排序方式
					productTypeId: '',
				},
				form: { // 添加或编辑表单对象初始化数据
					companyName: "",
					companyNameEn: "",
					standNo: "",
					stands: [],
					productTypeIds: [],
				},
				// 表单验证规则
				formValidate: {
					companyName: [{
						required: true,
						trigger: "blur",
						message: "请输入展商名称"
					}],
					companyNameEn: [{
						required: true,
						trigger: "blur",
						message: "请输入展商英文名称"
					}],
				},
				submitLoading: false, // 添加或编辑提交状态
				selectList: [], // 多选数据
				selectCount: 0, // 多选计数
				columns: [
					// 表头
					{
						type: "selection",
						width: 60,
						align: "center"
					},
					{
						type: "index",
						width: 60,
						align: "center"
					},
					{
						title: "展商名称",
						key: "companyName",
						minWidth: 120,
					},
					{
						title: "展商英文名称",
						key: "companyNameEn",
						minWidth: 120,
					},
					{
						title: "展位号",
						key: "standNo",
						minWidth: 100,
					},
					{
						title: "收藏数",
						key: "collectCount",
						minWidth: 80,
					},
					{
						title: "产品类别",
						key: "productTypes",
						width: 200,
						align: "center",
						render: (h, params) => {
							let str = params.row.productTypeNames;
							return h("div", {

							}, str ? str.join(',') : "")


						}
					},
					{
						title: "创建时间",
						key: "createTime",
						minWidth: 160,
						sortable: true,
					},
					{
						title: "更新时间",
						key: "updateTime",
						minWidth: 160,
						sortable: true,
					},
					{
						title: "操作",
						key: "action",
						align: "center",
						width: 120,
						fixed: "right",
						render: (h, params) => {
							return h("div", [
								h(
									'I', {
										class: 'ivu-icon ivu-icon-ios-create-outline',
										style: {
											marginRight: "5px",
											color: "#2d8cf0",
											'font-size': "28px",
											'font-weight': "bold",
											cursor: "pointer"
										},
										attrs: {
											title: "编辑",

										},

										on: {
											click: () => {
												this.edit(params.row);
											}
										}
									},

								),

								h(
									'i', {
										class: 'ivu-icon ivu-icon-ios-trash',
										style: {
											marginRight: "5px",
											color: "#ff5959",
											'font-size': "28px",
											cursor: "pointer"
										},
										attrs: {
											title: "删除",
										},

										on: {
											click: () => {
												this.remove(params.row);
											}
										}
									},

								)
							]);
						}
					}
				],
				data: [], // 表单数据
				pageNumber: 1, // 当前页数
				pageSize: 10, // 页面大小
				total: 0, // 表单数据总数

			};
		},
		methods: {

			init() {
				this.getDataList();
				this.getAllProductType();
			},

			changePage(v) {
				this.searchForm.pageNumber = v;
				this.getDataList();
				this.clearSelectAll();
			},
			changePageSize(v) {
				this.searchForm.pageSize = v;
				this.getDataList();
			},
			handleSearch() {
				this.searchForm.pageNumber = 1;
				this.searchForm.pageSize = 10;
				this.getDataList();
			},
			handleReset() {
				this.$refs.searchForm.resetFields();
				this.searchForm.pageNumber = 1;
				this.searchForm.pageSize = 10;
				// 重新加载数据
				this.getDataList();
			},
			changeSort(e) {
				this.searchForm.sort = e.key;
				this.searchForm.order = e.order;
				if (e.order === "normal") {
					this.searchForm.order = "";
				}
				this.getDataList();
			},
			clearSelectAll() {
				this.$refs.table.selectAll(false);
			},
			changeSelect(e) {
				this.selectList = e;
				this.selectCount = e.length;
			},
			getDataList() {
				this.loading = true;
				getExhibitorList(this.searchForm).then(res => {
					this.loading = false;
					if (res.success === true) {
						this.data = res.result.content;
						this.total = res.result.totalElements;
					}
				});
			},
			handleChild(arr) {
				if (arr && arr.length > 0) {
					for (let i = 0; i < arr.length; i++) {
						let a = arr[i];
						a.value=a.id;
						a.label=a.nameCn;
						a.children = this.handleChild(a.children);
					}
				}
				return arr;
			},
			//修改或添加时 更新产品类别的选中状态
			changeProductTypeOldValue(arr){
				if (arr && arr.length > 0 ) {
					for (let i = 0; i < arr.length; i++) {
						let a = arr[i];
						this.$set(a,'expand',this.productTypeIds.includes(a.id))
						if( !(a.children && a.children.length>0)){
							this.$set(a,'checked',this.productTypeIds.includes(a.id))
						}else{
							this.$set(a,'checked',false)
							this.$set(a,'disableCheckbox',true)
						}
						a.children = this.changeProductTypeOldValue(a.children);
					}
				}
				return arr;
			},
			getAllProductType() {
				getAllProductType().then(res => {
					if (res.success === true) {
						let arr = this.handleChild(res.result);
						this.productTypes = arr;
						this.productTypeTree = arr;
					}
				});
			},
			productChange(v) {
				this.form.productTypeIds = v.map((item,index)=>{
					return item.id;
				});
			},
			handleSubmit() {
				this.$refs.form.validate(valid => {
					if (valid) {
						if (this.form.stands.length === 0) {
							this.$Message.error('至少填写一个展位号');
							return;
						}
						this.form.standNo = this.form.stands.map((item, index) => {
							return item.value;
						}).join(',');
						this.submitLoading = true;

						if (this.modalType === 0) {
							// 添加 避免编辑后传入id等数据 记得删除
							delete this.form.id;
							addExhibitor(this.form).then(res => {
								this.submitLoading = false;
								if (res.success == true) {
									this.$Message.success("操作成功");
									this.getDataList();
									this.modalVisible = false;
								}
							});
						} else {
							// 编辑
							editExhibitor(this.form).then(res => {
								this.submitLoading = false;
								if (res.success == true) {
									this.$Message.success("操作成功");
									this.getDataList();
									this.modalVisible = false;
								}
							});

						}
					}
				});
			},
			//清空展位
			handleClearStand() {
				this.form.stands = [];
				this.standFlag++;
			},
			//添加展位
			handleAddStand(v = "") {
				this.form.stands.push({
					value: v
				});
				this.standFlag++;
			},

			handleRemoveStand(index) {
				this.form.stands.splice(index, 1);
				this.standFlag++;
			},
			add() {
				this.modalType = 0;
				this.modalTitle = "添加";
				this.$refs.form.resetFields();
				delete this.form.id;
				this.modalVisible = true;
				//清空展位
				this.handleClearStand();
				//添加展位
				this.handleAddStand();
				this.form.productTypeIds = [];
				this.productTypeIds=[];
			},
			edit(v) {

				this.modalType = 1;
				this.modalTitle = "编辑";
				this.$refs.form.resetFields();
				this.form.id = v.id;
				this.form.companyName = v.companyName;
				this.form.companyNameEn = v.companyNameEn;
				this.form.productTypeIds = v.productTypeIds;
				this.productTypeIds=v.productTypeIds;
				//清空展位
				this.handleClearStand();
				let arr = v.standNo ? v.standNo.split(',') : [];
				for (let a in arr) {
					//添加展位
					this.handleAddStand(arr[a]);
				}
				this.modalVisible = true;
			},
			remove(v) {
				this.$Modal.confirm({
					title: "确认删除",
					// 记得确认修改此处
					content: "您确认要删除 " + v.companyName + " ?",
					onOk: () => {
						// 删除
						this.operationLoading = true;
						deleteExhibitor(v.id).then(res => {
							this.operationLoading = false;
							if (res.success == true) {
								this.$Message.success("删除成功");
								this.getDataList();
							}
						});


					}
				});
			},
			delAll() {
				if (this.selectCount <= 0) {
					this.$Message.warning("您还未选择要删除的数据");
					return;
				}
				this.$Modal.confirm({
					title: "确认删除",
					content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
					onOk: () => {
						let ids = "";
						this.selectList.forEach(function(e) {
							ids += e.id + ",";
						});
						ids = ids.substring(0, ids.length - 1);
						this.operationLoading = true;
						deleteExhibitor(ids).then(res => {
							this.operationLoading = false;
							if (res.success == true) {
								this.$Message.success("删除成功");
								this.clearSelectAll();
								this.getDataList();
							}
						});
					}
				});
			},
			beforeUploadImport(file) {
				this.uploadfile = file;
				const fileExt = file.name
					.split(".")
					.pop()
					.toLocaleLowerCase();
				if (fileExt == "xlsx" || fileExt == "xls") {
					this.readFile(file);
					this.file = file;
				} else {
					this.$Notice.warning({
						title: "文件类型错误",
						desc: "所选文件‘ " +
							file.name +
							" ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。"
					});
				}
				return false;
			},
			// 读取文件
			readFile(file) {
				const reader = new FileReader();
				reader.readAsArrayBuffer(file);
				reader.onerror = e => {
					this.$Message.error("文件读取出错");
				};
				reader.onload = e => {
					this.$Message.success("读取数据成功");
					const data = e.target.result;
					const {
						header,
						results
					} = excel.read(data, "array");
					const tableTitle = tempColumns.map(item => {
						return {
							title: item.title,
							key: item.key
						};
					});
					excel.processResult(tempColumns, results);
					this.importTableData = results;
					this.importColumns = tableTitle;
				};
			},
			downloadTemple() {
				let title = [];
				let key = [];
				tempColumns.forEach(e => {
					title.push(e.title);
					key.push(e.key);
				});
				const params = {
					title: title,
					key: key,
					data: tempData,
					autoWidth: true,
					filename: "导入展商数据模版"
				};
				excel.export_array_to_excel(params);
			},
			initImportResult() {
				this.importResult = {
					successCount: 0,
					errorDataList: [],
				};
			},
			importData() {
				this.importLoading = true;
				this.initImportResult();
				importExhibitor(this.importTableData).then(res => {
					this.importLoading = false;
					if (res.success) {
						this.importModalVisible = false;
						this.getDataList();
						if (res.result) {
							this.importResult.successCount = res.result.successCount;
							let errorList = res.result.errorList;
							this.importResult.errorDataList = [];
							errorList.forEach(e => {
								let d = this.importTableData[e.row];
								d['failMsg'] = e.message;
								this.importResult.errorDataList.push(d);
							});
						}
						this.importModalResultVisible = true;

					}
				});
			},
			exportErrorData() {
				if (this.importResult.errorDataList && this.importResult.errorDataList.length > 0) {
					let title = [];
					let key = [];
					tempColumns.forEach(e => {
						title.push(e.title);
						key.push(e.key);
					});
					title.push("");
					key.push("failMsg");
					const params = {
						title: title,
						key: key,
						data: this.importResult.errorDataList,
						autoWidth: true,
						filename: "导入失败数据"
					};
					excel.export_array_to_excel(params);
				}

			},
searchProductTypeChange(v){
	this.searchForm.productTypeId=v?v[v.length-1]:"";
}
		},
		computed: {},
		// 监听对象的某些属性
		watch: {
        'productTypeIds': {
            handler(newValue, oldValue) {
                this.productTypes=this.changeProductTypeOldValue(this.productTypes);
            },
			 // 深度监听
            deep: true
        }
    },
		mounted() {

			this.init();
		}
	};
</script>
<style lang="less">
	.search {
		.operation {
			margin-bottom: 2vh;
		}

		.select-count {
			font-size: 13px;
			font-weight: 600;
			color: #40a9ff;
		}

		.select-clear {
			margin-left: 10px;
		}

		.page {
			margin-top: 2vh;
		}

		.drop-down {
			font-size: 13px;
			margin-left: 5px;
		}
	}

	.drawer-footer {
		z-index: 10;
		width: 100%;
		position: absolute;
		bottom: 0;
		left: 0;
		border-top: 1px solid #e8e8e8;
		padding: 10px 16px;
		text-align: right;
		background: #fff;
	}

	.drawer-footer {
		position: static;
	}

	.ivu-table-cell div {
		white-space: normal;
		word-break: break-all;
	}

	.ivu-modal-confirm-body div {
		word-break: break-all;
	}
</style>
